<?php
/**
 * Smart Library - Smart Framework
 * http://smart-framework.highet.eu
 *
 * @category   SmartL
 * @package    SmartL_DatabaseManager
 * @copyright  Copyright (c) 2005-2008 Smart Framework team - Stepan Sindelar, Vojtech Vit
 * @license    http://www.opensource.org/licenses/bsd-license.php	New BSD License
 */

/**
 * @see SmartL_DatabaseManager_Interface
 */
require_once 'SmartL/DatabaseManager/Interface.php';

require_once 'Zend/Db.php';

/**
 * Implementation of Database manager for Zend_Db.
 *
 * @package SmartL_DatabaseManager
 */
class SmartL_DatabaseManager_ZendDb implements SmartL_DatabaseManager_Interface {
	/**
	 * @var SmartL_DatabaseManager_ZendDb
	 */
	private static $_instance;
	
	/**
	 * Storage of all opened db connections.
	 * Index is name and value is object.
	 *
	 * @var array
	 */
	private $_connections = array ();
	
	/**
	 * Name of current connection
	 *
	 * @var string
	 */
	private $_currentName = null;
	
	protected function __construct() {
	}
	
	/**
	 * Opens connection.
	 *
	 * @param string name 
	 * @param array $options Array with options given in config. Value under index 'adapter'
	 * will be used as Zend_Db adapter name. Rest of array will be used options, ror more see Zend_Db manual.
	 * @exception SmartL_DatabaseManager_Exception When connection failed, or wrong options are given.
	 */
	public function openDbConnection($name, $options) {
		if (! isset ( $options ['adapter'] )) {
			require_once 'SmartL/DatabaseManager/Exception.php';
			throw new SmartL_DatabaseManager_Exception ( "Value of adapter in " . "options for method openDbConnection of SmartL_DatabaseManager_ZendDb missing" );
		}
		
		$adapter = $options ['adapter'];
		unset ( $options ['adapter'] );
		
		$this->_connections [$name] = Zend_Db::factory ( $adapter, $options );
	}
	
	/**
	 * Sets current connection for this manager.
	 * 
	 * Zend_Db doesn't have manager of all connections, so this
	 * is only for purposes of this class.
	 *
	 * @param string $name Name of current connection.
	 */
	public function setCurrentConnection($name) {
		$this->_currentName = $name;
	}
	
	/**
	 * @return string Name of current connection.
	 */
	public function getCurrentConnectionName() {
		return $this->_currentName;
	}
	
	/**
	 * Returns object of connection with given name.
	 *
	 * @param string $name
	 */
	public function getConnection($name) {
		return $this->_connections [$name];
	}
	
	/**
	 * @return string "ZendDb"
	 */
	public function getLibraryName() {
		return "ZendDb";
	}
	
	/**
	 * Implementation of singleton pattern.
	 *
	 * @return SmartL_DatabaseManager_ZendDb
	 */
	public static function getInstance() {
		if (self::$_instance == null) {
			self::$_instance = new SmartL_DatabaseManager_ZendDb ( );
		}
		return self::$_instance;
	}
}